const app = getApp();
const QQMapWX = require('../libs/qqmap-wx-jssdk.js');
const requireHttps = app.globalData.requireHttps //获取require域名
const WXBizDataCrypt = require('../../utils/RdWXBizDataCrypt.js');
let qqmapsdk
Page({
  data: {
    longitude: 113.324520,
    latitude: 23.099994,
    markers: [],
    hidden: '',
    showView: true,
    showFlag: true,
    bottomRpx: '',
    nearParking: [],
    markerId: '',
    is_show: 'hide',
    orderView: false,
    orderList: [],
    head: '',
    name: '',
    sex: '',
    phone: '',
    code: ''
  },
  onLaunch: function() {
    let _this = this
    
  },
  onLoad: function() {
    let _this = this
    
    _this.onGetLocation()
    _this.onGetUserInfo()
    _this.getMyOrderStatus()
    qqmapsdk = new QQMapWX({
      key: 'E5UBZ-T5NWJ-U7DFW-KO22C-XNONZ-4EBOY' //这里自己的key秘钥进行填充
    })

  },
  onShow: function() {
    let _this = this
    // _this.userIsYes()
    _this.getMyOrderStatus()
    qqmapsdk = new QQMapWX({
      key: 'E5UBZ-T5NWJ-U7DFW-KO22C-XNONZ-4EBOY' //这里自己的key秘钥进行填充
    })
  },
  //判断用户是否授权
  userIsYes: function() {
    let _this = this
    wx.getSetting({
      success: res => {
        if (!res.authSetting['scope.userInfo'] == true) {
          _this.onGetUserInfo()
        } else {
          _this.onGetUserInfo()
        }
        if (!res.authSetting['scope.userLocation'] == true) {
          _this.onGetLocation()
        } else {
        }
      }
    })
  },
  onGetLocation: function() {
    let _this = this
    //请求用户授权位置信息
    wx.getLocation({
      type: 'wgs84',
      success: res => {
        // console.log(res)
        //存储用户经纬度
        app.globalData.latitude = res.latitude //纬度
        app.globalData.longitude = res.longitude //经度
        _this.getLocal(app.globalData.latitude, app.globalData.longitude)
        _this.setData({
          wd: app.globalData.latitude,
          jd: app.globalData.longitude,
          showFlag: true
        })
        //发起网络请求获取用户附近车库
        wx.request({
          url: '' + requireHttps + '/api/garage/getNearGarage',
          data: {
            lat: app.globalData.latitude,
            lng: app.globalData.longitude
          },
          method: 'post',
          success: res => { //请求成功
            wx.hideLoading()
            // console.log(res)
            let data = res.data.data
            // console.log(data)
            let markers = []
            let marker = {}
            for (let i = 0; i < data.length; i++) {
              marker = {
                iconPath: '/pages/image/others.png',
                id: data[i].g_id,
                latitude: data[i].g_lat,
                longitude: data[i].g_lng,
                width: 36,
                height: 40,
                g_address: data[i].g_address,
                g_name: data[i].g_name,
                juli: data[i].juli,
                total: data[i].total,
                usable: data[i].usable
              }
              markers.push(marker)
              if (markers.length == data.length) {
                _this.setData({
                  markers: markers
                })
                // console.log(markers)
              }
            }
            // console.log(markers)
          },
          fail: error => { //请求失败
            console.log(error)
          }
        })
      },
      //获取地理位置失败(用户点击不允许)
      fail: error => {
        wx.hideLoading()
        _this.setData({
          showFlag: false
        })
      },
      complete: complete => {
        // wx.hideLoading()
      }
    })
  },
  // 获取当前地理位置
  getLocal: function(latitude, longitude) {
    let _this = this;
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: res => {
        // console.log(res);
        let province = res.result.ad_info.province
        let city = res.result.ad_info.city
        if (res.result.address.length > 15) {
          let address = res.result.address.substring(0, 15) + '...'
          _this.setData({
            address: address
          })
        } else {
          let address = res.result.address
          _this.setData({
            address: address
          })
        }
        _this.setData({
          province: province,
          city: city,
          latitude: latitude,
          longitude: longitude,
        })
      },
      fail: error => {
        console.log(error);
      }
    });
  },
  onReady: function() {
    let _this = this;
    // _this.chooseLocation();
  },
  chooseLocation: function() {
    let _this = this;
    wx.chooseLocation({
      success: res => {
        // console.log(res.address)
        _this.setData({
          address: res.address
        })
      }
    })
  },
  //用户不允许时的提示,点击时去设置
  getLocation: function() {
    
    let _this = this
    //获取经纬度
    wx.openSetting({
      success: res => {
        //判断是否获取用户位置信息
        if (res.authSetting['scope.userLocation']) {
          wx.getLocation({
            type: 'wgs84',
            success: res => {
              app.globalData.latitude = res.latitude
              app.globalData.longitude = res.longitude
              _this.getLocal(app.globalData.latitude, app.globalData.longitude)
              _this.setData({
                wd: app.globalData.latitude,
                jd: app.globalData.longitude,
                showFlag: true
              })
              //发起网络请求获取用户附近车库
              wx.request({
                url: '' + requireHttps + '/api/garage/getNearGarage',
                data: {
                  lat: app.globalData.latitude,
                  lng: app.globalData.longitude
                },
                method: 'post',
                success: res => { //请求成功
                  let data = res.data.data
                  _this.getMyOrderStatus()
                  // console.log(data)
                  let markers = []
                  let marker = {}
                  for (let i = 0; i < data.length; i++) {
                    marker = {
                      iconPath: '/pages/image/others.png',
                      id: data[i].g_id,
                      latitude: data[i].g_lat,
                      longitude: data[i].g_lng,
                      width: 36,
                      height: 40,
                      g_address: data[i].g_address,
                      g_name: data[i].g_name,
                      juli: data[i].juli,
                      total: data[i].total,
                      usable: data[i].usable
                    }
                    markers.push(marker)
                    if (markers.length == data.length) {
                      _this.setData({
                        markers: markers
                      })
                      // console.log(marker)

                    }
                  }
                },
                fail: error => { //请求失败
                  console.log(error)
                }
              })
            },
            //获取地理位置失败(用户点击不允许)时执行
            fail: function() {
              _this.setData({
                showFlag: false
              })
            }
          })
          _this.setData({
            showFlag: true
          })
        } else {
          //没有授权显示按钮
          _this.setData({
            showFlag: false
          })
        }
      },
      fail: error => {
        console.log(error)
      }
    })
  },
  //跳转附近车库
  bindViewTab: () => {
    wx.navigateTo({
      url: '/pages/parking/parking',
    })
  },
  //跳转附近车位
  openSetparking: function(e) {
    app.globalData.gid = e.currentTarget.dataset.gid
    app.globalData.g_address = e.currentTarget.dataset.g_address
    app.globalData.g_name = e.currentTarget.dataset.g_name
    app.globalData.juli = e.currentTarget.dataset.juli
    app.globalData.g_usable = e.currentTarget.dataset.usable
    wx.navigateTo({
      url: '/pages/setParking/setParking',
    })
  },
  //个人中心
  goUsercenter: () => {
    setTimeout(function() {
      wx.navigateTo({
        url: '/pages/userCenter/userCenter',
      })
    }, 150)

  },
  closeSetCar: function() {
    let _this = this;
    _this.setData({
      showView: (!_this.data.showView),
      bottomRpx: 20,
      markerId: ''
    })
  },
  //当用户点击地图标注
  getMarkerGo: function(e) {
    // console.log(e)
    let _this = this
    // let markerId = e.markerId
    _this.setData({
      markerId: e.markerId,
      showView: false,
      bottomRpx: 345,
      nearParking: e.currentTarget.dataset.markers
    })
  },
  getMyLocation: function() {
    let mpCtx = wx.createMapContext("map");
    mpCtx.moveToLocation();
  },
  //用户点击授权按钮
  onGetUserInfo: function() {
   
    let _this = this;
    wx.getSetting({
      success: res => {
        // console.log(res)
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，调用 getUserInfo 获取头像昵称
          wx.getUserInfo({
            success: res => {
              // console.log(res.userInfo)
              // app.globalData.userHead = res.userInfo.avatarUrl
              // app.globalData.userName = res.userInfo.userName
              //获取用户信息
              _this.setData({
                is_show: 'hide'
              })
              wx.showLoading({
                title: '加载中',
                mask: true
              })
              // 登录
              //调用微信登录接口，获取code
              wx.login({
                success: res => {
                  
                  //登录凭证
                  let code = res.code;
                  if (code) {

                    //传入token获取openid
                    wx.request({
                      url: '' + requireHttps + '/api/wechat/getToken',
                      data: {
                        code: code
                      },
                      method: "post",
                      success: res => {
                        // console.log(res);
                        //存储openid
                        app.globalData.openid = res.data.data.openid
                        //存储session_key
                        app.globalData.session_key = res.data.data.session_key
                        //解密用户信息获取openid unionid
                        let pc = new WXBizDataCrypt(app.globalData.APP_ID, app.globalData.session_key)

                        //获取用户信息
                        wx.getUserInfo({
                          success: res => {
                            // console.log(res);
                            app.globalData.userHead = res.userInfo.avatarUrl
                            app.globalData.userName = res.userInfo.nickName
                            //定义变量接收解密后的encryptedData
                            let data = pc.decryptData(res.encryptedData, res.iv)
                            // console.log(data)
                            // app.globalData.unionid = data.unionId
                            _this.data.head = data.avatarUrl;
                            _this.data.name = data.nickName;
                            _this.data.sex = res.userInfo.gender;
                            _this.data.phone = '';
                            _this.data.code = code
                            //用户注册
                            wx.request({
                              url: '' + requireHttps + '/api/wechat/userReg',
                              data: {
                                head: _this.data.head,
                                name: _this.data.name,
                                sex: _this.data.sex,
                                phone: _this.data.phone,
                                openid: app.globalData.openid,
                                unionid: '',
                                code_token: code
                              },
                              method: 'post',
                              success: res => {
                                // console.log(res);
                                //注册成功获取用户token
                                app.globalData.token = res.data.data.token;
                                //获取用户信息
                                wx.request({
                                  url: '' + requireHttps + '/api/member/getMemberInfo',
                                  data: {
                                    token: app.globalData.token
                                  },
                                  method: 'post',
                                  success: res => {
                                    //存储合作物业审核状态
                                    app.globalData.audit_status = res.data.data.audit_status;
                                    //存储我的车牌号
                                    app.globalData.card = res.data.data.card;
                                    //存储客服电话
                                    app.globalData.callServer = res.data.data.service_call;
                                    //存储用户余额
                                    app.globalData.balance = res.data.data.money;
                                    app.globalData.codeImgPath = res.data.data.code_img;
                                    _this.getMyOrderStatus()
                                    wx.hideLoading()
                                    //存储用户信息
                                    _this.setData({
                                      head: res.data.data.head,
                                      code_img: res.data.data.code_img,
                                      money: app.globalData.balance,
                                      name: res.data.data.name,
                                      phone: res.data.data.phone,
                                      service_call: app.globalData.service_call,
                                      sex: app.globalData.sex
                                    })
                                  }
                                })
                              }
                            })
                          }
                        })
                      }
                    })
                  }
                },
                fail: () => {
                  console.log('登陆失败')
                }
              })
            }
          })
        } else {
          //没有授权显示按钮
          _this.setData({
            is_show: ''
          })
        }
      }
    })
  },
  setLocation: function() {
    let _this = this
    wx.chooseLocation({
      
      success: res => { //成功
        //存储用户选择位置
        app.globalData.latitude = res.latitude
        app.globalData.longitude = res.longitude
        wx.getLocation({
          type: 'wgs84',
          success: function(res) {
            _this.setData({
              wd: app.globalData.latitude,
              jd: app.globalData.longitude,
              showFlag: true
            })
          },
        })
        // console.log(res.address)
        if (res.address.length > 15) {
          let address = res.address.substring(0, 15) + '...'
          _this.setData({
            address: address
          })
        } else {
          let address = res.address
          _this.setData({
            address: address
          })
        }
      },
      fail: error => { //调起失败
        console.log(error)
      }
    })
  },
  forOrder: function() {
    let _this = this
    wx.navigateTo({
      url: '/pages/myOrder/myOrder',
    })
  },
  getMyOrderStatus: function() {
    // wx.showLoading({
    //   title: '加载中',
    //   mask: true
    // })
    // console.log(app.globalData.token)
    //发起网络请求获取 用户订单信息
    let _this = this
    if (app.globalData.token == '') {
      _this.onGetUserInfo()
    }
    wx.request({
      url: '' + requireHttps + '/api/order/getUserOrderList',
      data: {
        token: app.globalData.token,
        page: 1,
        lng: app.globalData.longitude,
        lat: app.globalData.latitude
      },
      method: 'post',
      success: res => {
        // console.log(res)
        // wx.hideLoading();
        if (res.data.message == 'token已失效') {
          _this.onGetUserInfo()
          console.log('token已失效')
        }
        if (res.data.code == -1) {
          _this.onGetUserInfo()
          console.log('code: -1')
        }
        if (res.data.data == '') {
          _this.setData({
            orderView: false
          })
        } else {
          for (let i = 0; i < res.data.data.length; i++) {
            if (res.data.data[i].o_status == 1) {
              _this.setData({
                orderList: res.data.data,
                orderView: true
              })
              return false
            } else {
              _this.setData({
                orderView: false
              })
            }
          }
        }
      }
    })
  }
})